package edu.gdut.thesissys.service;

import java.text.SimpleDateFormat;
import java.util.Set;

import javax.annotation.Resource;

import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import edu.gdut.thesissys.action.director.GraduationScheduleAction;
import edu.gdut.thesissys.dao.DaoFactory;
import edu.gdut.thesissys.vo.GraduationSchedule;
import edu.gdut.thesissys.vo.Major;

public class GraduationScheduleService {
	private static final Logger log = LoggerFactory
			.getLogger(GraduationScheduleService.class);
	@Resource(name = "daoFactory")
	private DaoFactory daoFactory;

	/**
	 * 保存或更新graduationSchedule
	 * 
	 * @param action
	 * @return 保存成功返回"{true}"，异常返回"{false}"
	 */
	@Transactional
	public String saveOrUpdateSchedule(GraduationScheduleAction action) {
		GraduationSchedule gs = new GraduationSchedule();
		log.debug("save or update schedule...");
		try {
			// 注入数据到对象
			gs.setMajor(daoFactory.getBaseDAO(Major.class).findById(
					action.getMajorId()));
			gs.setPaperTitleDate(action.getPaperTitleDate());
			gs.setGraduationGrade(action.getGraduationGrade());
			gs.setDoubleChooseStartDate(action.getDoubleChooseStartDate());
			gs
					.setDoubleFirstChooseEndDate(action
							.getDoubleFirstChooseEndDate());
			gs.setDoubleChooseEndDate(action.getDoubleChooseEndDate());
			gs.setChoosePapetTitleDate(action.getChoosePapetTitleDate());
			gs.setTaskBookStartDate(action.getTaskBookStartDate());
			gs.setTaskBookEndDate(action.getTaskBookEndDate());
			gs.setMidCheckDate(action.getMidCheckDate());
			gs.setAccreditationOneEndDate(action.getAccreditationOneEndDate());
			gs.setAccreditationOneStartDate(action
					.getAccreditationOneStartDate());
			gs.setAccreditationTwoEndDate(action.getAccreditationTwoEndDate());
			gs.setAccreditationTwoStartDate(action
					.getAccreditationTwoStartDate());
			gs.setPublicDebateEndDate(action.getPublicDebateEndDate());
			gs.setPublicDebateStartDate(action.getPublicDebateStartDate());
			gs.setCommonDabateEndDate(action.getCommonDabateEndDate());
			gs.setCommonDabateStartDate(action.getCommonDabateStartDate());

			Integer id = isScheduleExist(gs);
			// 存在，注入已经存在的graduationScheduleId
			if (id != null) {
				gs.setGraduationScheduleId(id);
			}

			daoFactory.getBaseDAO(GraduationSchedule.class).attachDirty(gs);// 保存或者更新

			log.debug("save successful and return {true}");
			return "{true}";
		} catch (Exception e) {
			log.error("save graduationSchedule error", e);
			return "{false}";
		}
	}

	/**
	 * 检测graduationSchedule是否存在
	 * 
	 * @param schedule
	 *            要检测的对象
	 * @return 存在返回对应graduationScheduleId，不存在或者异常返回null
	 */
	@Transactional(readOnly = true)
	public Integer isScheduleExist(GraduationSchedule schedule) {
		Integer scheduleId = null;
		log.debug("checck if schedule is exist");
		try {
			Set<GraduationSchedule> graduationSchedules = schedule.getMajor()
					.getGraduationSchedules();
			for (GraduationSchedule scheduleInstance : graduationSchedules) {
				if (scheduleInstance.getGraduationGrade().trim()
						.equalsIgnoreCase(schedule.getGraduationGrade().trim())) {
					scheduleId = scheduleInstance.getGraduationScheduleId();// 存在，返回graduationScheduleId
					daoFactory.getBaseDAO(GraduationSchedule.class)
							.attachClean(scheduleInstance);// 将查询到的对象转换为瞬息状态
				}
			}
		} catch (Exception e) {
			log.error("check exist of graduationSchedule failed", e);
			return null;
		}
		log.debug("check schedule successful and return " + scheduleId);
		return scheduleId;
	}

	/**
	 * 查询graduationSchedule
	 * 
	 * @param majorId
	 *            专业id
	 * @param grade
	 *            年级
	 * @return 存在返回查找到的对象，不存或者异常在返回null
	 */
	public GraduationSchedule findSchedule(int majorId, String grade) {
		GraduationSchedule schedule = null;
		log.debug("find graduationSchedule by majorId and grade :[" + majorId
				+ ", " + grade + "]");
		try {
			Set<GraduationSchedule> graduationSchedules = daoFactory
					.getBaseDAO(Major.class).findById(majorId)
					.getGraduationSchedules();
			for (GraduationSchedule scheduleInstance : graduationSchedules) {
				if (scheduleInstance.getGraduationGrade().trim()
						.equalsIgnoreCase(grade.trim())) {
					schedule = scheduleInstance;
				}
			}
		} catch (Exception e) {
			log.error("find graduationSchedule failed", e);
			return null;
		}
		log.debug("find graduationSchedule successful and return " + schedule);
		return schedule;
	}

	/**
	 * 输出GraduationSchedule对象的json格式
	 * 
	 * @param schedule
	 *            GraduationSchedule 对象
	 * @return eg:
	 *         {"publicDebateEndDate":"2012-05-18","midCheckDate":"2012-05-18"
	 *         ,"commonDabateEndDate"
	 *         :"2012-05-11","paperTitleDate":"2012-06-20",
	 *         "taskBookEndDate":"2012-05-11"
	 *         ,"choosePapetTitleDate":"2012-06-02"
	 *         ,"accreditationOneStartDate":"2012-05-08"
	 *         ,"commonDabateStartDate":
	 *         "2012-05-23","doubleChooseEndDate":"2012-06-10"
	 *         ,"taskBookStartDate"
	 *         :"2012-05-11","majorId":1,"accreditationOneEndDate"
	 *         :"2012-05-08","doubleChooseStartDate"
	 *         :"2012-06-01","graduationGrade"
	 *         :"2012","accreditationTwoStartDate"
	 *         :"2012-05-14","accreditationTwoEndDate"
	 *         :"2012-05-14","doubleFirstChooseEndDate"
	 *         :"2012-06-02","graduationScheduleId":1}
	 */
	@SuppressWarnings("unchecked")
	public JSONObject getScheduleJson(GraduationScheduleAction action) {
		JSONObject scheduleJson = new JSONObject();
		GraduationSchedule schedule = findSchedule(action.getMajorId(), action
				.getGraduationGrade());
		log
				.debug("transform GraduationSchedule instance into json "
						+ schedule);
		try {
			SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
			scheduleJson.put("graduationScheduleId", schedule
					.getGraduationScheduleId());
			scheduleJson.put("majorId", schedule.getMajor().getMajorId());
			scheduleJson.put("graduationGrade", schedule.getGraduationGrade());
			scheduleJson.put("accreditationOneEndDate", formater
					.format(schedule.getAccreditationOneEndDate()));
			scheduleJson.put("accreditationOneStartDate", formater
					.format(schedule.getAccreditationOneStartDate()));
			scheduleJson.put("accreditationTwoEndDate", formater
					.format(schedule.getAccreditationTwoEndDate()));
			scheduleJson.put("accreditationTwoStartDate", formater
					.format(schedule.getAccreditationTwoStartDate()));
			scheduleJson.put("choosePapetTitleDate", formater.format(schedule
					.getChoosePapetTitleDate()));
			scheduleJson.put("commonDabateEndDate", formater.format(schedule
					.getCommonDabateEndDate()));
			scheduleJson.put("commonDabateStartDate", formater.format(schedule
					.getCommonDabateStartDate()));
			if (schedule.getDoubleChooseEndDate() != null
					&& schedule.getDoubleChooseStartDate() != null
					&& schedule.getDoubleFirstChooseEndDate() != null) {
				scheduleJson.put("doubleChooseEndDate", formater
						.format(schedule.getDoubleChooseEndDate()));
				scheduleJson.put("doubleChooseStartDate", formater
						.format(schedule.getDoubleChooseStartDate()));
				scheduleJson.put("doubleFirstChooseEndDate", formater
						.format(schedule.getDoubleFirstChooseEndDate()));
			}
			scheduleJson.put("midCheckDate", formater.format(schedule
					.getMidCheckDate()));
			scheduleJson.put("paperTitleDate", formater.format(schedule
					.getPaperTitleDate()));
			scheduleJson.put("publicDebateEndDate", formater.format(schedule
					.getPublicDebateEndDate()));
			scheduleJson.put("taskBookEndDate", formater.format(schedule
					.getTaskBookEndDate()));
			scheduleJson.put("taskBookStartDate", formater.format(schedule
					.getTaskBookStartDate()));
		} catch (Exception e) {
			log.error("transform GraduationSchedule failed", e);
			return new JSONObject();
		}
		return scheduleJson;
	}

	/**
	 * 判断专业是否为信管系
	 * 
	 * @param majorId
	 *            专业id
	 * @return 是返回ture，否或者异常返回false
	 */
	public boolean isXinguan(int majorId) {
		boolean result = false;
		log.debug("check whether major " + majorId + " is xinguan");
		try {
			Major major = daoFactory.getBaseDAO(Major.class).findById(majorId);
			if (major != null
					&& major.getDepartment().getName().equals("信息管理工程系")) {
				result = true;
			}
		} catch (Exception e) {
			log.error("check major failed", e);
			return false;
		}
		log.debug("check major successful and return " + result);
		return result;
	}
}
